package com.lianxi.okttp;

import okhttp3.*;
import org.junit.Test;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Proxy;

public class DemoOKTTP {

    private static OkHttpClient okHttpClient = new OkHttpClient();



    // 设置代理服务地址
    private static OkHttpClient proxyHttpClient =
            new OkHttpClient.Builder()
                    .proxy(new Proxy(Proxy.Type.HTTP,new InetSocketAddress("192.168.80.128",13579)))
                    .build();

    public static void main(String[] args) {
        DemoOKTTP demoOKTTP = new DemoOKTTP();
        demoOKTTP.testAsyGet();
    }


    @Test
    public void testAsyGet() {
        //1.创建OkHttpClient对象
        //2.创建Request对象，设置一个url地址（百度地址）,设置请求方式。(方法名敏感，需要大写)
        Request request = new Request.Builder().url("http://www.baidu.com").method("GET", null).build();
        //3.创建一个call对象,参数就是Request请求对象
        Call call = proxyHttpClient.newCall(request);
        //4.请求加入调度，重写回调方法
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                System.out.println(call);
                System.out.println("失败了..."+e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                System.out.println("执行成功了。。。");
                System.out.println(response.body().string());
            }
        });
    }


    @Test
    public void testAsyPost() {
        RequestBody formBody = new FormBody.Builder()
                .add("size", "10")
                .build();
        Request request = new Request.Builder()
                .url("http://api.1-blog.com/biz/bizserver/article/list.do")
                .post(formBody)
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String str = response.body().string();
                new Thread(new Runnable() {
                    @Override
                    public void run() {

                    }
                });
            }
        });

    }


}
